'use strict';
const path = require('path');
const Spinner = require('cli-spinner').Spinner;

function isObject(o) {
  return Object.prototype.toString.call(o) === '[object Object]'
}

function formatPath(p){
  if(p && typeof p === 'string'){
    const sep = path.sep; // 获取当前操作系统的路径分隔符, windows是\, linux和mac是/
    if(sep === '/'){
      return p
    }
    return p.replace(/\\/g, '/')
  }
  return p
}

function spinnerStart(msg = 'loading...', str = '|/-\\'){
  const spinner = new Spinner(msg + ' %s');
  spinner.setSpinnerString(str);
  spinner.start();
  return spinner
}

function sleep(timeout = 1000){
  return new Promise(resolve => {
    setTimeout(resolve, timeout)
  })
}

// (在子进程执行node命令)兼容windows和mac操作系统
function exec(cmd, args, options) {
  const win32 = process.platform === 'win32'
  const command = win32 ? 'cmd' : cmd
  const cmdArgs = win32 ? ['/c', command].concat(args) : args
  return require('child_process').spawn(command, cmdArgs, options || {})
}

function execSync(cmd, args, options) {
  return new Promise((resolve, reject) => {
    const p = exec(cmd, args, options)
    p.on('error', reject)
    p.on('exit', code => {
      resolve(code)
    })
  })
}

module.exports = {
  isObject,
  formatPath,
  spinnerStart,
  sleep,
  exec,
  execSync
}
